package com.it.sun.easychat.framework.websocket;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.scheduling.concurrent.DefaultManagedTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @author sunmannian
 * @ClassName WebSocketConfiguration
 * @Date 2020/5/23 22:16
 * @Version V1.0
 * Description  <请输入一句话描述该类功能>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/5/23
 */
@EnableWebSocketMessageBroker
@Configuration
@Slf4j
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 揿动一个websocket端点
        registry.addEndpoint("/msg-socket").
                setAllowedOrigins("*").
                addInterceptors().
                withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 注册两个通道
        registry.enableSimpleBroker("/topic", "/queue").
                //设置心跳
                        setHeartbeatValue(new long[]{0, 10000L}).
                // 设置默认的任务调度器
                        setTaskScheduler(new DefaultManagedTaskScheduler());
        // 用户订阅频道的前缀即向用户发送消息时的前缀
        registry.setUserDestinationPrefix("/user");
        // 用户发送消息的前缀，即接收用户发送消息的前缀
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.
                        getAccessor(message, StompHeaderAccessor.class);
                // 建立连接的请求
                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    String username = accessor.getFirstNativeHeader("username");
                    String password = accessor.getFirstNativeHeader("password");
                    String userID = accessor.getFirstNativeHeader("userID");
                    Assert.notBlank(userID, "消息中心无法获取当前登录用户信息");
                    log.info("user========>{}进入消息中心", userID);
                    // 将用户登录消息中心信息存入redis
                    redisTemplate.opsForValue().set(userID, userID);
                }
                return message;
            }

            @Override
            public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {

            }
        });
    }
}
